package com.fx.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.fx.entity.*;
import com.fx.service.CstInfoService;
import com.fx.service.SysResService;
import com.fx.service.SysUserService;
import com.fx.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sysUser")
public class SysUserController extends BaseController {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysResService sysResService;
    @Autowired
    CstInfoService cstInfoService;
    private static String pageTitle = "用户管理";
    private static String pageUrl = "/sysUser";


    @RequestMapping()
    public String intoView(Model model) {
        model.addAttribute("pageInfo", PageInfo.getInstance(pageUrl, pageTitle, Constant.LIST_TITLE));
        return "sysUser/list";
    }

    @RequestMapping("/listData")
    @ResponseBody
    public JSONObject listData(@RequestParam Map<String, Object> param) {
        Query p = new Query(param);
        List<SysUser> data = sysUserService.listData(p);
        int count = sysUserService.getCount(p);
        return renderPage(count, data);
    }

    @RequestMapping("/add")
    public String add(Model model) {
        model.addAttribute("pageInfo", PageInfo.getInstance(pageUrl, pageTitle, Constant.ADD_TITLE));
        return "sysUser/add";
    }

    @RequestMapping("/edit/{flId}")
    public String edit(Model model, @PathVariable("flId") String flId) {
        SysUser sysUser = sysUserService.getById(flId);
        model.addAttribute("pageInfo", PageInfo.getInstance(pageUrl, pageTitle, Constant.EDIT_TITLE));
        model.addAttribute("sysUser", sysUser);
        return "sysUser/edit";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public R saveOrUpdate(SysUser sysUser) {
        Object pwd = sysUser.getFlLoginPwd();
        String id = sysUser.getFlId();
        if (pwd != null && !"".equals(pwd)) {
            sysUser.setFlLoginPwd(MD5Util.digestHex(pwd.toString()));
        }
        int result = 0;
        if (id == null || "".equals(id)) {
            result = sysUserService.save(sysUser);
        } else {
            result = sysUserService.updateById(sysUser);
        }
        if (result != 0) {
            return R.ok("操作成功!");
        }
        return R.error("操作失败!");
    }

    @RequestMapping("/batchDel")
    @ResponseBody
    public R batchDel(@RequestParam("ids") String[] ids) {
        int result = 0;
        result = sysUserService.batchDelByIds(ids);
        if (result != 0) {
            return R.ok("操作成功!");
        }
        return R.error("操作失败!");
    }

    @RequestMapping("/login")
    @ResponseBody
    public R getSysUserById(HttpServletRequest request, String fl_login_name, String fl_login_pwd, String imgCode) {
        if (imgCode != null) {
            imgCode = imgCode.toUpperCase();
        }
        fl_login_pwd = MD5Util.digestHex(fl_login_pwd);
        UsernamePasswordToken token = new UsernamePasswordToken(fl_login_name, fl_login_pwd);
        Subject subject = SecurityUtils.getSubject();
        String generaImgCode = request.getSession().getAttribute(Constant.IMG_CODE) == null ? "" : request.getSession().getAttribute(Constant.IMG_CODE).toString().toUpperCase();
        if (true || generaImgCode.equals(imgCode)) {
            try {
                subject.login(token);
                request.getSession().setAttribute(Constant.ADMIN_SESSION, SecurityUtils.getSubject().getPrincipal());
                AdminTempUser sysUser = (AdminTempUser) SecurityUtils.getSubject().getPrincipal();
                Integer type = sysUser.getFlType();
                if (type == 1) {
                    //系统用户
                    SysUser user = new SysUser();
                    user.setFlId(sysUser.getFlId());
                    String firstLogin = sysUser.getFlFirstLoginTime();
                    if (firstLogin == null || "".equals(firstLogin)) {
                        user.setFlFirstLoginTime(DateUtil.now());
                    }
                    user.setFlLastLoginTime(DateUtil.now());
                    sysUserService.updateById(user);
                }else if(type == 0){
                    //客户
                    CstInfo cstInfo = new CstInfo();
                    cstInfo.setFlId(sysUser.getFlId());
                    cstInfo.setFlLastLoginTime(DateUtil.now());
                    cstInfoService.updateById(cstInfo);
                }
                return R.ok();
            } catch (LockedAccountException e) {
                return R.error("账号被锁定，请联系管理员！");
            } catch (AuthenticationException e) {
                return R.error("密码错误");
            }
        }
        request.getSession().removeAttribute(Constant.IMG_CODE);
        return R.error("验证码错误!");
    }

    @RequestMapping("/index")
    public String index(HttpServletRequest request, Model model) {
        AdminTempUser sysUser = (AdminTempUser) SecurityUtils.getSubject().getPrincipal();
        String roleId = sysUser.getFlRoleId();
        List<Tree<SysRes>> res = sysResService.getResListByRoleId(roleId);
        SysCustomSetting setting = sysUserService.getCurrentSettingByUserId(sysUser.getFlId());
        model.addAttribute("res", res);
        model.addAttribute("setting", setting);
        return "index";
    }

    @RequestMapping("/saveCustomSetting")
    public void saveCustomSetting(@RequestParam Map<String, Object> param) throws Exception {
        AdminTempUser sysUser = (AdminTempUser) SecurityUtils.getSubject().getPrincipal();
        param.put("userId", sysUser.getFlId());
        sysUserService.updateCurrentUserSetting(param);
    }

    @RequestMapping("/img")
    public void img(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ICaptcha captcha = CaptchaUtil.createCircleCaptcha(Constant.CAPTCHA_WIDTH, Constant.CAPTCHA_HEIGHT);
        String imgCode = captcha.getCode();
        request.getSession().setAttribute(Constant.IMG_CODE, imgCode);
        captcha.write(response.getOutputStream());
    }

    @RequestMapping("/updatePwd")
    @ResponseBody
    public R updatePwd(@RequestParam Map<String, Object> param) {
        String flId = ((SysUser) SecurityUtils.getSubject().getPrincipal()).getFlId();
        Object oldPwd = param.get("old_pwd");
        Object newPwd = param.get("new_pwd");
        param.clear();
        SysUser user = sysUserService.getById(flId);
        if (user != null) {
            String tempOldPwd = MD5Util.digestHex(String.valueOf(oldPwd));
            String dbPwd = user.getFlLoginPwd();
            if (tempOldPwd.equals(dbPwd)) {
                String tempNewPwd = MD5Util.digestHex(String.valueOf(newPwd));
                user.setFlLoginPwd(tempNewPwd);
                if (sysUserService.updateById(user) != 0) {
                    return R.ok("密码修改成功");
                }
                return R.error("密码修改失败");
            }
            return R.error("旧密码错误");
        }
        return R.error("密码修改失败");
    }

    @GetMapping("/logout")
    String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }
}
